<template>
  <div>
    <el-card>

      <!--搜索框与按钮-->
      <el-row :gutter="20">
        <el-col :span="8">

          <el-input placeholder="输入关键字查询"
                    v-model="queryInfo.query"
                    clearable
                    @clear="getTableList">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getTableList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <el-button type="primary"
                     @click="addDialogVisible=true"
                     icon="el-icon-circle-plus-outline"
                     style="width:100%">新增</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="danger"
                     @click="deleteRecordByIds"
                     icon="el-icon-remove-outline"
                     style="width:100%">批量删除</el-button>
        </el-col>
        <el-col :span="3">
          <el-button type="success"
                     @click="deleteRecordByIds"
                     icon="el-icon-download"
                     style="width:100%">导出EXCEL</el-button>
        </el-col>

        <!-- 表格列筛选 -->
        <el-col :span="2"
                :offset="5">
          <el-popover placement="right"
                      width=""
                      trigger="click">
            <el-checkbox-group v-model="tableFilterData.checkBoxList">
              <template v-for="(item, i) in tableFilterData.dataNow">
                <el-checkbox :label="item.attr"
                             :key="i"
                             :checked="item.checked"
                             style="display: block;margin:10px;"
                             @change="filterFunHandle('filter',item.attr,i)">
                  {{item.label}}
                </el-checkbox>
              </template>
            </el-checkbox-group>
            <el-button size="small"
                       slot="reference"><i class="el-icon-arrow-down el-icon-menu" /> 列筛选</el-button>
            <el-button size="small"
                       type="text"
                       @click="filterFunHandle('allchecked')">全选</el-button>
            <el-button size="small"
                       type="text"
                       @click="filterFunHandle('cancel')">取消全选</el-button>
          </el-popover>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="tableFilterData.dataList"
                border
                stripe
                size="medium"
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection">
        </el-table-column>

        <!-- 依次渲染表格的每列 -->
        <template v-for="(col,index) in tableFilterData.dataNow">
          <!-- 如果当前列的attr为普通类型，渲染内容即可 -->
          <el-table-column :key="index"
                           v-if="col.checked===true &&col.attr!=='state' && col.attr!=='type'"
                           align="center"
                           :prop="col.attr"
                           :label="col.label">
          </el-table-column>
          <!-- 如果当前列的attr为state，渲染为switch开关形式 -->
          <el-table-column :key="index"
                           v-if="col.checked===true &&col.attr==='state'"
                           :label="col.label">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.state"
                         active-value="1"
                         inactive-value="0"
                         @change="switchStateChanged(scope.row)">
              </el-switch>
            </template>
          </el-table-column>
          <!-- 如果当前列的attr为type，渲染为标签形式 -->
          <el-table-column :key="index"
                           v-if="col.checked===true &&col.attr==='type'"
                           :label="col.label"
                           :prop="col.attr">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.type == '0'">标签一</el-tag>
              <el-tag v-if="scope.row.type == '1'"
                      type="success">标签二</el-tag>
            </template>
          </el-table-column>
          <!-- 如果当前列的attr为url，渲染为图片形式 -->
          <el-table-column :key="index"
                           v-if="col.checked===true &&col.attr==='url' "
                           :label="col.label"
                           :prop="col.attr">
            <template slot-scope="scope">
              <el-image style="width: 100px; height: 100px"
                        :src="scope.row.url"
                        :fit="'contain'"
                        :preview-src-list="[scope.row.url]">
              </el-image>
            </template>
          </el-table-column>
        </template>

        <el-table-column label="操作"
                         width="180px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="showEditDialog(scope.row)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="deleteRecordById(scope.row.id)"></el-button>
            <!-- 查看详情按钮 -->
            <el-tooltip effect="dark"
                        content="查看详情"
                        placement="top"
                        :enterable="false">
              <el-button type="success"
                         icon="el-icon-tickets"
                         size="mini"
                         @click="getDetailInfo(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>

      </el-table>

      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="this.queryInfo.pagenum"
                     :page-sizes="[3, 7, 15, 20, 30]"
                     :page-size="this.queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total"></el-pagination>

      <!-- 点击按钮的弹出框以及详细信息抽屉区域 -->
      <el-drawer title="我是标题"
                 :visible.sync="drawerVisible"
                 :with-header="false">
        <span>我来啦!</span>
      </el-drawer>
      <!-- 添加记录的对话框 -->
      <el-dialog title="添加记录"
                 :visible.sync="addDialogVisible"
                 @close="addDialogClosed"
                 width="50%">
        <!-- 内容主体区 -->
        <el-form :model="addForm"
                 :rules="addFormRules"
                 ref="addFormRef"
                 label-width="100px">
          <el-form-item label="维修记录编号">
            <el-input v-model="addForm.repairRecordId"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="物料表id"
                        prop="materialId">
            <el-input v-model="addForm.materialId"></el-input>
          </el-form-item>
          <el-form-item label="物料名"
                        prop="materialName">
            <el-input v-model="addForm.materialName"></el-input>
          </el-form-item>
          <el-form-item label="数量"
                        prop="num">
            <el-input v-model="addForm.num"></el-input>
          </el-form-item>

        </el-form>
        <!-- 底部区域 -->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="addRecord">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改记录对话框 -->
      <el-dialog title="修改记录"
                 :visible.sync="editDialogVisible"
                 width="50%"
                 @close="editDialogClosed">
        <el-form :model="editForm"
                 :rules="editFormRules"
                 ref="editFormRef"
                 label-width="100px">
          <el-form-item label="维修记录编号">
            <el-input v-model="editForm.repairRecordId"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="物料表id"
                        prop="materialId">
            <el-input v-model="editForm.materialId"></el-input>
          </el-form-item>
          <el-form-item label="物料名"
                        prop="materialName">
            <el-input v-model="editForm.materialName"></el-input>
          </el-form-item>
          <el-form-item label="数量"
                        prop="num">
            <el-input v-model="editForm.num"></el-input>
          </el-form-item>

        </el-form>
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="editRecordInfo">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>
<script>
import {
  getList,
  add,
  deleteSelected,
  deleteCurrent,
  getEditInfo,
  edit,
  getDetail,
  modifySwitch,
} from "@/api/logistics/logisticsGreen.js";
export default {
  data () {
    return {
      // 表格列筛选数据
      tableFilterData: {
        dataList: [
          {
            id: "1",
            repairRecordId: "102",
            materialId: "1",
            materialName: "灯管",
            num: "5",
          },
          {
            id: "2",
            repairRecordId: "103",
            materialId: "2",
            materialName: "空调",
            num: "10",
          },
        ],
        dataNow: [
          { label: "	序号	", attr: "id", checked: false },
          { label: "	维修记录编号	", attr: "repairRecordId", checked: true },
          { label: "	物料表id	", attr: "materialId", checked: false },
          { label: "	物料名	", attr: "materialName", checked: true },
          { label: "	数量	", attr: "num", checked: true },

        ],

        checkLabels: [], // 筛选列显示多选框数据
        checkBoxList: [], // 筛选列数据
        indexTwo: 0,
      },
      // 记录列表分页区的参数
      queryInfo: {
        //搜索条件
        query: "",
        // 当前页码
        pagenum: 1,
        //每页显示条数
        pagesize: 7,
      },
      total: 24,


      // 控制添加记录对话框的显示与隐藏
      addDialogVisible: false,
      // 添加记录的表单数据
      addForm: {
        id: "",
        repairRecordId: "",
        materialId: "",
        num: "",

      },
      // 添加表单校验规则
      addFormRules: {},


      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      // 编辑表单校验规则
      editFormRules: {},


      // 控制详细信息抽屉的显示与隐藏
      drawerVisible: false,
      // 详细信息的表单数据
      detailForm: {},
      // 被选中的记录id
      selectedList: []
    }
  },
  created () {

  },
  methods: {
    // 获取列表信息
    async getTableList () {
      await getList(
        this.queryInfo.pagenum,
        this.queryInfo.pagesize,
        this.queryInfo.query
      ).then((res) => {
        if (res.data.code !== 200) {
          return this.$message.error('获取表格数据失败!')
        }
        this.tableList = res.data.data.list
        this.total = res.data.data.total

        console.log(res)
      })

    },

    // 监听多选框选中的所有记录
    handleSelectionChange (val) {
      this.selectedList = val;
    },
    // 监听pagesize改变的事件
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryinfo.pagesize = newSize
      this.getTableList()
    },
    // 监听页码值改变的事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryinfo.pagenum = newPage
      this.getTableList()
    },
    // 监听添加对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改对话框的关闭
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 表头列筛选功能
    filterFunHandle (type, currentItem, index) {
      if (type === 'filter') { // 筛选列
        if (event.target.checked === false) {
          this.tableFilterData.dataNow.forEach((item, index, arr) => {
            if (item.attr === currentItem) {
              return item.checked = false
            }
          })
        } else {
          this.tableFilterData.dataNow.forEach((item, index, arr) => {
            if (item.attr === currentItem) {
              return item.checked = true
            }
          })
        }
      } else if (type === 'allchecked') { // 全选
        if (this.tableFilterData.checkLabels.length === 0) {
          this.tableFilterData.dataNow.forEach((result) => {
            this.tableFilterData.checkLabels.push(result.attr)
          })
          this.tableFilterData.checkBoxList = this.tableFilterData.checkLabels // 复选框置为复选所有值，全部选择    
        } else {
          this.tableFilterData.checkBoxList = this.tableFilterData.checkLabels // 复选框置为复选所有值，全部选择
        }
        this.tableFilterData.dataNow.forEach((item, index, arr) => {
          item.checked = true
        })
      } else if (type === 'cancel') { // 取消全选
        this.tableFilterData.checkBoxList = [] // 复选框置为空，全部不选择
        this.tableFilterData.dataNow.forEach((item, index, arr) => {
          item.checked = false
        })
      }
    },






    // 添加记录
    addRecord () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加记录的网络请求
        await add(
          this.addForm.name,
          this.addForm.password,
          this.addForm.phone,
          this.addForm.roleId
        ).then((res) => {
          if (res.meta.status !== 201) {
            this.$message.error('添加记录失败！')
          }
          this.$message.success('添加记录成功！')
          // 隐藏添加记录的对话框
          this.addDialogVisible = false
          // 重新获取记录列表数据
          this.getTableList()
        })
      })
    },
    // 删除（批量）
    async deleteRecordByIds () {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，返回值为字符串confirm
      // 如果用户取消删除，返回值未字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      await deleteSelected(this.selectedList).then((res) => {
        if (res.meta.status !== 200) {
          return this.$message.error('删除记录失败！')
        }
        this.$message.success('删除记录成功！')
        this.getTableList()
      })

    },
    // 查看修改记录（当前记录）
    async showEditDialog (rowInfo) {
      this.editForm = rowInfo
      this.editDialogVisible = true
    },
    // 确认修改
    editRecordInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改记录信息的数据请求
        await edit(
          this.editForm.id,
          this.editForm.email,
          this.editForm.mobile
        ).then((res) => {
          if (res.meta.status !== 200) {
            return this.$message.error('更新信息失败！')
          }
          // 关闭对话框
          this.editDialogVisible = false
          // 刷新数据列表
          this.getTableList()
          // 提示修改成功
          this.$message.success('更新信息成功！')
        })

      })
    },
    // 删除（当前记录）
    async deleteRecordById (id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，返回值为字符串confirm
      // 如果用户取消删除，返回值未字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      await deleteCurrent(id).then((res) => {
        if (res.meta.status !== 200) {
          return this.$message.error('删除记录失败！')
        }
        this.$message.success('删除记录成功！')
        this.getTableList()
      })

    },
    // 查看详情（当前记录）
    async getDetailInfo (rowInfo) {
      this.detailForm = rowInfo
      this.drawerVisible = true
    },
    // 修改switch开关状态（当前记录）
    async switchStateChanged (recordinfo) {
      console.log(recordinfo)
      await modifySwitch(recordinfo.id, recordinfo.state).then((res) => {
        if (res.data.code !== 200) {
          recordinfo.state = !recordinfo.state
          return this.$message.error('更新状态失败!')
        }
        this.$message.success('更新状态成功!')
      })

    },

  }

}


</script>
<style scoped>
.el-table {
  font-size: 13px;
}
.el-pagination {
  text-align: left;
  padding-top: 20px;
}
</style>